package com.chenyi.framework.web.service;

import com.chenyi.common.config.ChenYiConfig;
import com.chenyi.common.constant.Constants;
import com.chenyi.common.core.domain.model.LoginAdmin;
import com.chenyi.common.core.redis.RedisCache;
import com.chenyi.common.exception.BadRequestException;
import com.chenyi.common.exception.MessageException;
import com.chenyi.common.utils.DateUtils;
import com.chenyi.common.utils.MessageUtils;
import com.chenyi.common.utils.StringUtils;
import com.chenyi.framework.manager.AsyncManager;
import com.chenyi.framework.manager.factory.AsyncFactory;
import com.chenyi.system.mapper.SysAdminMapper;
import com.chenyi.system.service.ISysAdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;

/**
 * 登录校验方法
 * 
 * @author wangkh
 */
@Component
public class AdminLoginService
{
    @Autowired
    private AdminTokenService tokenService;

    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private SysAdminMapper adminMapper;

    /**
     * 登录验证
     * 
     * @param username 用户名
     * @param password 密码
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public String login(String username, String password, String code, String uuid)
    {
        String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;
        String captcha = redisCache.getCacheObject(verifyKey);
        redisCache.deleteObject(verifyKey);
        if (captcha == null)
        {
            AsyncManager.me().execute(AsyncFactory.recordAdminLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire"),null));
            throw new MessageException(MessageUtils.message("user.jcaptcha.expire"));
        }
        if (!code.equalsIgnoreCase(captcha))
        {
            AsyncManager.me().execute(AsyncFactory.recordAdminLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error"),null));
            throw new MessageException(MessageUtils.message("user.jcaptcha.error"));
        }
        // 用户验证
        Authentication authentication = null;
        try
        {
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager
                    .authenticate(new UsernamePasswordAuthenticationToken(username, password));
        }
        catch (Exception e)
        {
            if (e instanceof BadCredentialsException)
            {
                AsyncManager.me().execute(AsyncFactory.recordAdminLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match"),null));
                throw new MessageException(MessageUtils.message("user.password.not.match"));
            }
            else
            {
                AsyncManager.me().execute(AsyncFactory.recordAdminLogininfor(username, Constants.LOGIN_FAIL, e.getMessage(),null));
                throw new BadRequestException(e.getMessage());
            }
        }

        LoginAdmin loginAdmin = (LoginAdmin) authentication.getPrincipal();

        //清理上次Token
        if (StringUtils.isNotEmpty(loginAdmin.getAdmin().getToken()) && ChenYiConfig.getAdminSsoLogin()){
            tokenService.delLoginAdmin(loginAdmin.getAdmin().getToken());
            //其它地方登录记录
            AsyncManager.me().execute(AsyncFactory.recordAdminLogininfor(loginAdmin.getUsername(), Constants.LOGIN_FAIL, MessageUtils.message("user.otherlogout"),loginAdmin.getAdmin().getToken()));
        }

        // 生成token
        String token = tokenService.createToken(loginAdmin);
        AsyncManager.me().execute(AsyncFactory.recordAdminLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success"),loginAdmin.getToken()));

        loginAdmin.getAdmin().setToken(loginAdmin.getToken());
        loginAdmin.getAdmin().setLoginDate(new Date(loginAdmin.getLoginTime()));
        loginAdmin.getAdmin().setLoginIp(loginAdmin.getIpaddr());
        loginAdmin.getAdmin().setUpdateTime(DateUtils.getNowDate());
        adminMapper.updateAdmin(loginAdmin.getAdmin());

        return token;
    }
}
